<template>
  <a-modal
    v-model:open="open"
    :closable="false"
    :confirm-loading="confirmLoading"
    :title="title"
    okText="下载"
    @ok="handleOk"
  >
    <a-form layout="vertical" :model="req">
      <a-form-item
        label="下载地址:"
        v-if="req.cate != Category.BitTorrent"
        :rules="[{ required: true }]"
      >
        <a-textarea
          v-model:value="req.uri"
          placeholder="请输入"
          :auto-size="{ minRows: rows, maxRows: rows }"
          allow-clear
        />
        <span v-if="!toBatch" class="batch-btn" @click="onBatch">
          批量下载
        </span>
      </a-form-item>
      <a-form-item
        label="BT文件:"
        v-if="req.cate == Category.BitTorrent"
        :rules="[{ required: true }]"
      >
        <a-upload
          :maxCount="1"
          :beforeUpload="onBeforeUpload"
          @remove="onRemove"
        >
          <a-button>
            <UploadOutlined />
            上传
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="下载目录:">
        <a-textarea
          v-model:value="req.dir"
          placeholder="使用默认目录"
          :auto-size="{ minRows: 2, maxRows: 3 }"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="任务名称:" v-if="!toBatch">
        <a-textarea
          v-model:value="req.name"
          placeholder="不输入自动生成"
          :auto-size="{ minRows: 2, maxRows: 3 }"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { Category, useApisStore, type AddReq } from "@/stores/apis";
import { computed, ref } from "vue";
import { UploadOutlined } from "@ant-design/icons-vue";
import { App, Upload, type UploadFile } from "ant-design-vue";

const { message } = App.useApp();
const apis = useApisStore();
const emit = defineEmits(["after"]);
const open = ref(false);
const confirmLoading = ref(false);
const req = ref<AddReq>({ uri: "", cate: Category.File });
const title = computed(() => {
  switch (req.value.cate) {
    case Category.File:
      return "文件";
    case Category.Magnet:
      return "磁力";
    case Category.BitTorrent:
      return "BT";
  }
});
const toBatch = ref(false);
const rows = ref(4);

function openModal(type: Category) {
  open.value = true;
  req.value = { uri: "", cate: type };
  toBatch.value = false;
  rows.value = 4;
}

defineExpose({ openModal });

function onBatch() {
  toBatch.value = true;
  rows.value = 10;
}

function onBeforeUpload(file: UploadFile) {
  if (file.type != "application/x-bittorrent") {
    message.error("只能上传.torrent文件，请重新上传");
    return Upload.LIST_IGNORE;
  }
  const reader = new FileReader();
  reader.onload = () => {
    req.value.name = file.name;
    req.value.uri = reader.result as string;
    const i = req.value.uri.indexOf(",");
    if (i >= 0) {
      req.value.uri = req.value.uri.slice(i + 1);
    }
  };
  reader.readAsDataURL(file as any);
  return false;
}

function onRemove() {
  req.value.uri = "";
}

function handleOk() {
  if (!req.value.uri) {
    message.error(
      req.value.cate == "BitTorrent" ? "BT文件不能为空" : "下载地址不能为空"
    );
    return;
  }
  confirmLoading.value = true;
  download()
    .then(() => {
      open.value = false;
      emit("after");
    })
    .catch((error) => message.error(error))
    .finally(() => {
      confirmLoading.value = false;
    });
}

async function download() {
  if (toBatch.value) {
    const uris = req.value.uri.split("\n");
    for (const uri of uris) {
      req.value.uri = uri;
      await apis.addTask(req.value);
    }
    message.success("批量任务已创建");
  } else {
    const msg = await apis.addTask(req.value);
    message.success(msg);
  }
}
</script>

<style scoped>
.batch-btn {
  font-size: 12px;
  color: #002c8c;
  cursor: pointer;
}
</style>
